import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/net/interceptor.dart';

import 'errorhandle.dart';
enum METHODTYPE {

  GET(name: 'GET',value: 'GET'),
  POST(name: 'POST',value: 'POST'),
  PUT(name: 'PUT',value: 'PUT'),
  DELETE(name: 'DELETE',value: 'DELETE');

  final String name;
  final String value;

  const METHODTYPE({required this.name,required this.value});
}
class DioUtil{

  static final DioUtil _singleton = DioUtil._internal();

  static DioUtil get instance => DioUtil();

  factory DioUtil(){
    return _singleton;
  }

  static Dio? _dio;
  static Dio? get dio => _dio;
  String _baseUrl = ApiConfig.baseUrl;
  DioUtil._internal() {
    var baseOptions = BaseOptions(
      connectTimeout: Duration(seconds: 5),
      receiveTimeout: Duration(seconds: 5),
      responseType: ResponseType.json,
      validateStatus: (status){
        return true;
      },
      baseUrl: _baseUrl
    );
    _dio = Dio(baseOptions);
    if(kDebugMode)_dio!.interceptors.add(LoggingInterceptor());
    _dio!.interceptors.add(AdapterInterceptor());
  }
  //初始化dio
  initDio({String? baseUrl}){
    _baseUrl=baseUrl??'';
  }

  //添加拦截器
  DioUtil addInterceptor({Interceptor? interceptor}){
    if(interceptor!=null)_dio?.interceptors?.add(interceptor);
    return this;
  }
  //切换baseUrl
  DioUtil setBaseUrl({String? baseUrl}){
    if((baseUrl??'').isEmpty){
      _dio?.options?.baseUrl=_baseUrl;
    }else{
      _dio?.options?.baseUrl=baseUrl??_baseUrl;
    }
    return this;
  }

  Future request(
      String url, {
      METHODTYPE? methodtype,
      dynamic data,
      Map<String, dynamic>? queryParameters,
        bool? isFormData,
        List<MultipartFile>?  multipartFiles,
        CancelToken? cancelToken,
        List<Map<String,dynamic>>? addHeaders,
        bool? isSetToken,
      ProgressCallback? onSendProgress,
      ProgressCallback? onReceiveProgress
  }) async{
   FormData? formData;
   if((isFormData??false)){
     formData = FormData.fromMap(data);
     if((multipartFiles??[]).isNotEmpty){
       multipartFiles!.forEach((element){
         formData!.files.add(MapEntry('files', element));
       });
     }
   }
   try{
     Response? response = await _dio?.request(
       url,
       data: (isFormData??false)?formData:data,
       queryParameters: queryParameters,
       options: _checkOptions(methodtype,addHeaders,isSetToken)
     );
     print('--->get response=${response?.toString()}');
   }catch(e){
     var handleError = Errorhandle.handleError(e);
     print('--->get handleError=${handleError?.toString()}');

   }
  }

  Options _checkOptions(METHODTYPE? methodtype, List<Map<String,dynamic>>? addHeaders,bool? isSetToken) {
    Options options = Options(headers: {});
    if((addHeaders??[]).isNotEmpty){
      addHeaders?.forEach((element) {
        options.headers!.addAll(element);
      });
    }
    // if(isSetToken??true)options.headers!.addAll({'token':'${SpUtil.getString(ConstantUtil.spToken)}'});
    options.method = (methodtype??METHODTYPE.GET).value;
    return options;
  }
}